package com.novellotus.iov.carvice.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.RxCarCheckBean;
import com.novellotus.iov.carvice.model.AddServiceModel;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * 新增售后
 */
public class AddFailureActivity extends BaseActivity implements AMapLocationListener, AddServiceModel.AddServiceModelInterface {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.img_location)
    ImageView img_location;
    @BindView(R.id.edt_plate)
    MaterialEditText edt_plate;
    @BindView(R.id.edt_location)
    TextView edt_location;
    @BindView(R.id.edt_name)
    EditText edt_name;
    @BindView(R.id.edt_mobile)
    EditText edt_mobile;
    @BindView(R.id.edt_des)
    EditText edt_des;
    @BindView(R.id.btn_sure)
    Button btn_sure;
    String chooseType = "";
    String[] chooseKeys;
    AddServiceModel addServiceModel;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient locationClient = null;
    //  private GeocodeSearch geocoderSearch;
    private String plate = "", vin = "";
    private double lat, lng;
    private int type;//0可以改车牌  1不可以改车牌

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_service);
    }

    @Override
    public void init() {
        getMylocation();
        tv_tittle.setText("一键救援");
        addServiceModel = new AddServiceModel(this, this);
        addServiceModel.setPlateEdit(edt_plate);
        addServiceModel.setLocationEdit(edt_location);
        addServiceModel.setNameEdit(edt_name);
        addServiceModel.setMobileEdit(edt_mobile);
        addServiceModel.setDetailEdit(edt_des);
        addServiceModel.confirm(btn_sure);
        addServiceModel.setSubmitBtn(btn_sure);
        //初始数据

        if (getIntent().getExtras() != null) {
            plate = getIntent().getExtras().getString("plate", "");
            if (plate != null && plate.length() != 0) {
                edt_plate.setText(plate);
            }
        }
        edt_name.setText(SharedPreferencesUtils.getUser(this)[0]);
        edt_mobile.setText(SharedPreferencesUtils.getUser(this)[1]);
    }

    private void getMylocation() {
        locationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        locationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(200000);
//设置定位参数
        locationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        locationClient.startLocation();
    }

    /**
     * 定位
     */
    private void getLocation(final double lat, final double lng) {
//        Observable.create(new ObservableOnSubscribe<CharSequence>() {
//            @Override
//            public void subscribe(ObservableEmitter<CharSequence> e) throws Exception {
//                e.onNext("go");
//            }
//        }).compose(RxSchedulers.<CharSequence>composeIo()).subscribe(new Consumer<CharSequence>() {
//            @Override
//            public void accept(CharSequence o) throws Exception {
//                LatLonPoint latLonPoint = new LatLonPoint(lat, lng);
//                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.GPS);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//                MyUtils.logInformation("开始搜索地址");
//                geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
//            }
//        });
    }

    @OnClick(R.id.img_back)
    void back() {
        MyUtils.hideInput(this);
        finish();
    }

    @OnClick(R.id.img_location)
    void chooseLocation() {
        openForResultActivity(ChooseAddressActivity.class);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyUtils.logInformation(requestCode + "");
        if (resultCode == 1000 && data != null) {
            edt_location.setText(data.getStringExtra("address"));
            addServiceModel.setLocation(data.getDoubleExtra("lat", 0), data.getDoubleExtra("lng", 0));

        } else if (resultCode == 2000 && data != null) {
            chooseType = data.getStringExtra("type");
            chooseKeys = data.getStringArrayExtra("keys");
            // tv_type.setText(chooseType);
            addServiceModel.setKeys(chooseKeys);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                lat = amapLocation.getLatitude();//获取纬度
                lng = amapLocation.getLongitude();//获取经度
                MyUtils.logInformation(lat + "--" + lng);
                addServiceModel.setLocation(lat, lng);
                amapLocation.getAccuracy();//获取精度信息
                edt_location.setText(amapLocation.getCity() + amapLocation.getAddress());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                edt_location.setText("");
            }
        }
    }

//    @Override
//    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
//        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
//            if (result != null && result.getRegeocodeAddress() != null
//                    && result.getRegeocodeAddress().getFormatAddress() != null) {
//                String addressName = result.getRegeocodeAddress().getFormatAddress()
//                        + "附近";
//                edt_location.setText(addressName);
//            } else {
//                edt_location.setText("无法定位当前车辆位置");
//            }
//        } else {
//            edt_location.setText("无法定位当前车辆位置");
//        }
//    }
//
//    @Override
//    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
//
//    }

    @Override
    public void checkPass(RxCarCheckBean response) {
        if (response != null) {
            //   tv_vin.setText(response.getData().getVin());
            getLocation(response.getData().getLat(), response.getData().getLng());
        } else {
            //    tv_vin.setText("");
            edt_location.setText("");
        }
    }

    @Override
    public void updateMarkerCount(int count) {
        //    tv_marker_count.setText(count + "/" + 120);
    }


}
